from dash import Dash, dcc, html
from dash.dependencies import Input, Output, State
from src.common.descriptors.user_desc_lib import UserDescribe
from src.common.utils.wraper_fig import wraper_fig
from src.core.usage.software_usage import software_usage_day, software_usage_week, software_usage_total
from src.common.descriptors.user_desc_lib import weeks, days

def register_callbacks(app):
    @app.callback(
        Output('date-value-select', 'options'),
        Output('date-value-select', 'disabled'),
        Input('date-type-select', 'value')
    )
    def update_date_options(selected_type):
        if selected_type == 'week':
            options = [{'label': f"{start.strftime('%Y-%m-%d')} 至 {end.strftime('%Y-%m-%d')}", 
                      'value': i} for i, (start, end) in enumerate(weeks)]
            return options, False
        elif selected_type == 'day':
            options = [{'label': d.strftime('%Y-%m-%d'), 
                      'value': i} for i, d in enumerate(days)]
            return options, False
        else:
            return [], True

    @app.callback(
        Output('software_usage', 'src'),
        Input('submit-button', 'n_clicks'),
        [
            State('input-id', 'value'),
            State('date-type-select', 'value'),
            State('date-value-select', 'value')
        ],
        prevent_initial_call=True
    )
    def update_dashboard(n_clicks, input_id, date_type, date_value):
        if not input_id:
            return ""
            
        user = UserDescribe(user_id=input_id)
        
        if date_type == 'week' and date_value is not None:
            fig = software_usage_week(weeks[date_value], user.user_softwares)
        elif date_type == 'day' and date_value is not None:
            fig = software_usage_day(days[date_value], user.user_softwares)
        else:
            fig = software_usage_total(user.user_softwares)
            
        return wraper_fig(fig)

def create_layout():
    return html.Div(
        children=[
            html.Header([
                html.H1('📈 使用情况分析', 
                       style={'color': '#2c3e50', 'marginBottom': '20px'}),
                html.Div([
                    html.Div(
                        dcc.Input(
                            id='input-id',
                            type='text',
                            placeholder='请输入用户ID...',
                            debounce=True,
                            style={
                                'width': '100%',
                                'padding': '12px',
                                'border': '2px solid #3498db',
                                'borderRadius': '8px',
                                'fontSize': '16px',
                                'marginBottom': '10px'
                            }
                        )
                    ),
                    html.Div([
                        dcc.Dropdown(
                            id='date-type-select',
                            options=[
                                {'label': '总计', 'value': 'total'},
                                {'label': '周', 'value': 'week'},
                                {'label': '日', 'value': 'day'}
                            ],
                            value='total',
                            clearable=False,
                            style={
                                'flex': '1',
                                'marginRight': '10px',
                                'minWidth': '120px'
                            }
                        ),
                        dcc.Dropdown(
                            id='date-value-select',
                            disabled=True,
                            placeholder='请选择日期范围',
                            style={
                                'flex': '2',
                                'marginRight': '10px',
                                'minWidth': '200px'
                            }
                        ),
                        html.Button(
                            '分析用户 🔍',
                            id='submit-button',
                            n_clicks=0,
                            style={
                                'padding': '12px 24px',
                                'backgroundColor': '#3498db',
                                'color': 'white',
                                'border': 'none',
                                'borderRadius': '8px',
                                'cursor': 'pointer',
                                'flexShrink': '0'
                            }
                        )
                    ], style={
                        'display': 'flex',
                        'gap': '10px',
                        'alignItems': 'center',
                        'width': '100%'
                    })
                ], style={
                    'maxWidth': '800px',
                    'margin': '0 auto',
                    'padding': '20px'
                })
            ], style={
                'backgroundColor': '#f8f9fa',
                'padding': '2rem',
                'boxShadow': '0 2px 4px rgba(0,0,0,0.1)'
            }),

            html.Main([
                html.Div([
                    html.Article([
                        html.H2('💻 应用使用分析', style={'color': '#34495e', 'marginBottom': '15px'}),
                        dcc.Loading(
                            id='software-usage-loading',
                            type='circle',
                            children=html.Div(
                                html.Img(
                                    id='software_usage',
                                    style={
                                        'maxWidth': '100%',
                                        'height': 'auto',
                                        'objectFit': 'contain',
                                        'display': 'block'
                                    }
                                ),
                                style={
                                    'backgroundColor': 'white',
                                    'padding': '20px',
                                    'borderRadius': '8px',
                                    'boxShadow': '0 2px 4px rgba(0,0,0,0.05)',
                                    'margin': '0 auto'
                                }
                            )
                        )
                    ], style={'margin': '10px'})
                ], style={
                    'maxWidth': '1200px',
                    'margin': '0 auto',
                    'padding': '0 20px'
                })
            ], style={'padding': '20px'})
        ],
        style={
            'fontFamily': 'Segoe UI, system-ui',
            'minHeight': '100vh',
            'backgroundColor': '#ecf0f1'
        }
    )

def init_usage_dash(server):
    app = Dash(
        __name__,
        server=server,
        url_base_pathname='/usage/'
    )

    app.layout = create_layout()
    register_callbacks(app)

    return app